//
//  HYBaseTableViewController.m
//  HYNeiHan
//
//  Created by 上官惠阳 on 16/9/26.
//  Copyright © 2016年 上官惠阳. All rights reserved.
//

#import "HYBaseTableViewController.h"
#import "HYBaseTableHeaderFooterView.h"
#import "MJExtension.h"
#import "UIView+Tap.h"
#import "UIView+Layer.h"
#import "MJRefresh.h"

@interface HYBaseTableViewController ()
@property (nonatomic, copy) HYTableVcCellSelectedHandle handle;
@property (nonatomic, weak) UIImageView *refreshImg;
@end

@implementation HYBaseTableViewController
@synthesize needCellSepLine = _needCellSepLine;
@synthesize sepLineColor = _sepLineColor;
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray new];
    }
    return _dataArray;
}

/**
 *  加载tableview
 */
- (HYBaseTableView *)tableView {
    if(!_tableView){
        HYBaseTableView *tab = [[HYBaseTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        [self.view addSubview:tab];
        _tableView = tab;
        tab.dataSource = self;
        tab.delegate = self;
        tab.backgroundColor = [UIColor whiteColor];
        tab.separatorColor = kSeperatorColor;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //????????????
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
}

#pragma mark - loading & alert
- (void)HY_showLoading {

}

- (void)HY_hiddenLoading {

}

- (void)HY_showTitle:(NSString *)title after:(NSTimeInterval)after {

}

/** 添加空界面文字*/
- (void)HY_addEmptyPageWithText:(NSString *)text {

}
/** 设置刷新类型*/
- (void)setRefreshType:(HYBaseTableVcRefreshType)refreshType {
    _refreshType = refreshType;
    switch (refreshType) {
        case HYBaseTableVcRefreshTypeNone: // 没有刷新
            break ;
        case HYBaseTableVcRefreshTypeOnlyCanRefresh: { // 只有下拉刷新
            [self HY_addRefresh];
        } break ;
        case HYBaseTableVcRefreshTypeOnlyCanLoadMore: { // 只有上拉加载
            [self HY_addLoadMore];
        } break ;
        case HYBaseTableVcRefreshTypeRefreshAndLoadMore: { // 下拉和上拉都有
            [self HY_addRefresh];
            [self HY_addLoadMore];
        } break ;
        default:
            break ;
    }
}
- (void)setShowRefreshIcon:(BOOL)showRefreshIcon {
    _showRefreshIcon = showRefreshIcon;
    self.refreshImg.hidden = !showRefreshIcon;
}

- (UIImageView *)refreshImg {
    if (!_refreshImg) {
        UIImageView *refreshImg = [[UIImageView alloc] init];
        [self.view addSubview:refreshImg];
        _refreshImg = refreshImg;
        [self.view bringSubviewToFront:refreshImg];
        refreshImg.image = [UIImage imageNamed:@"refresh"];
        WeakSelf(weakSelf);
        [refreshImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf.view).mas_offset(-15);
            make.size.mas_equalTo(CGSizeMake(44, 44));
            make.bottom.mas_equalTo(weakSelf.view).mas_offset(-20);
        }];
        refreshImg.layerCornerRadius = 22;
        refreshImg.backgroundColor = kWhiteColor;

        [refreshImg setTapActionWithBlock:^{
            [self startAnimation];
            [weakSelf HY_beginRefresh];
        }];
    }
    return _refreshImg;
}

- (void)startAnimation {
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    rotationAnimation.duration = 1.5;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = MAXFLOAT;
    [self.refreshImg.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

- (void)endRefreshIconAnimation {
    [self.refreshImg.layer removeAnimationForKey:@"rotationAnimation"];
}

/** 需要系统分割线*/
- (void)setNeedCellSepLine:(BOOL)needCellSepLine {
    _needCellSepLine = needCellSepLine;
    self.tableView.separatorStyle = needCellSepLine ? UITableViewCellSeparatorStyleSingleLine : UITableViewCellSeparatorStyleNone;
}

- (BOOL)needCellSepLine {
    return self.tableView.separatorStyle == UITableViewCellSeparatorStyleSingleLine;
}

- (void)HY_addRefresh {
    [HYUtils addPullRefreshForScrollView:self.tableView pullRefreshCallBack:^{
        [self HY_refresh];
    }];
}

- (void)HY_addLoadMore {
    [HYUtils addLoadMoreForScrollView:self.tableView loadMoreCallBack:^{
        [self HY_loadMore];
    }];
}

/** 表视图偏移*/
- (void)setTableEdgeInset:(UIEdgeInsets)tableEdgeInset {
    _tableEdgeInset = tableEdgeInset;
    [self.view setNeedsUpdateConstraints];
    [self.view updateConstraintsIfNeeded];
    [self.view layoutIfNeeded];
    [self.view setNeedsLayout];
}

- (void)updateViewConstraints {
    [super updateViewConstraints];
    WeakSelf(weakSelf);

//    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(weakSelf.view).mas_offset(weakSelf.tableEdgeInset);
//    }];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.tableView.frame = self.view.bounds;
    [self.view sendSubviewToBack:self.tableView];
}
/** 分割线颜色*/
- (void)setSepLineColor:(UIColor *)sepLineColor {
    if (!self.needCellSepLine) return;
    _sepLineColor = sepLineColor;

    if (sepLineColor) {
        self.tableView.separatorColor = sepLineColor;
    }
}

- (UIColor *)sepLineColor {
    return _sepLineColor ? _sepLineColor : [UIColor whiteColor];
}

/** 刷新数据*/
- (void)HY_reloadData {
    [self.tableView reloadData];
}

/** 开始下拉*/
- (void)HY_beginRefresh {
    if (self.refreshType == HYBaseTableVcRefreshTypeOnlyCanRefresh || self.refreshType == HYBaseTableVcRefreshTypeRefreshAndLoadMore) {
        [HYUtils beginPullRefreshForScrollView:self.tableView];
    }
}

/** 刷新*/
- (void)HY_refresh {
    if (self.refreshType == HYBaseTableVcRefreshTypeNone || self.refreshType == HYBaseTableVcRefreshTypeOnlyCanLoadMore) {
        return ;
    }
    self.isRefresh = YES;
    self.isLoadMore = NO;
}

/** 上拉加载*/
- (void)HY_loadMore {
    if (self.refreshType == HYBaseTableVcRefreshTypeNone || self.refreshType == HYBaseTableVcRefreshTypeOnlyCanRefresh) {
        return ;
    }
    if (self.dataArray.count == 0) {
        return ;
    }
    self.isRefresh = NO;
    self.isLoadMore = YES;
}

- (void)HY_commonConfigResponseWithResponse:(id)response isRefresh:(BOOL)isRefresh modelClass:(__unsafe_unretained Class)modelClass {
    [self HY_commonConfigResponseWithResponse:response isRefresh:isRefresh modelClass:modelClass emptyText:nil];
}

- (void)HY_commonConfigResponseWithResponse:(id)response isRefresh:(BOOL)isRefresh modelClass:(__unsafe_unretained Class)modelClass emptyText:(NSString *)emptyText {
    if ([response isKindOfClass:[NSArray class]] == NO) return ;
    if (self.isRefresh) { // 刷新
        // 停止刷新
        [self HY_endRefresh];

        // 设置模型数组
        [self.dataArray removeAllObjects];
        self.dataArray = [modelClass mj_objectArrayWithKeyValuesArray:response];

        // 设置空界面占位文字
        if (emptyText.length) {
            [self HY_addEmptyPageWithText:emptyText];
        }

        // 刷新界面
        [self HY_reloadData];

    } else { // 上拉加载
        // 停止上拉
        [self HY_endLoadMore];

        // 没有数据提示没有更多了
        if ([response count] == 0) {
            [self HY_noticeNoMoreData];
        } else {
            // 设置模型数组
            NSArray *newModels = [modelClass mj_objectArrayWithKeyValuesArray:response];
            if (newModels.count < 50) {
                [self HY_hiddenLoadMore];
            }
            [self.dataArray addObjectsFromArray:newModels];

            // 刷新界面
            [self HY_reloadData];
        }
    }
}

/** 停止刷新*/
- (void)HY_endRefresh {
    if (self.refreshType == HYBaseTableVcRefreshTypeOnlyCanRefresh || self.refreshType == HYBaseTableVcRefreshTypeRefreshAndLoadMore) {
        [HYUtils endRefreshForScrollView:self.tableView];
    }
}

/** 停止上拉加载*/
- (void)HY_endLoadMore {
    if (self.refreshType == HYBaseTableVcRefreshTypeOnlyCanLoadMore || self.refreshType == HYBaseTableVcRefreshTypeRefreshAndLoadMore) {
        [HYUtils endLoadMoreForScrollView:self.tableView];
    }
}

/** 隐藏刷新*/
- (void)HY_hiddenRrefresh {
    if (self.refreshType == HYBaseTableVcRefreshTypeOnlyCanRefresh || self.refreshType == HYBaseTableVcRefreshTypeRefreshAndLoadMore) {
        [HYUtils hiddenHeaderForScrollView:self.tableView];
    }
}

/** 隐藏上拉加载*/
- (void)HY_hiddenLoadMore {
    if (self.refreshType == HYBaseTableVcRefreshTypeOnlyCanLoadMore || self.refreshType == HYBaseTableVcRefreshTypeRefreshAndLoadMore) {
        [HYUtils hiddenFooterForScrollView:self.tableView];
    }
}

/** 提示没有更多信息*/
- (void)HY_noticeNoMoreData {
    if (self.refreshType == HYBaseTableVcRefreshTypeOnlyCanLoadMore || self.refreshType == HYBaseTableVcRefreshTypeRefreshAndLoadMore) {
        [HYUtils noticeNoMoreDataForScrollView:self.tableView];
    }
}

/** 头部正在刷新*/
- (BOOL)isHeaderRefreshing {
    return [HYUtils headerIsRefreshForScrollView:self.tableView];
}

//* 尾部正在刷新
- (BOOL)isFooterRefreshing {
    return [HYUtils footerIsLoadingForScrollView:self.tableView];
}

#pragma mark - <UITableViewDataSource, UITableViewDelegate>
// 分组数量
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([self respondsToSelector:@selector(HY_numberOfSections)]) {
        return self.HY_numberOfSections;
    }
    return 0;
}

// 指定组返回的cell数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([self respondsToSelector:@selector(HY_numberOfRowsInSection:)]) {
        return [self HY_numberOfRowsInSection:section];
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if ([self respondsToSelector:@selector(HY_headerAtSection:)]) {
        return [self HY_headerAtSection:section];
    }
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if ([self respondsToSelector:@selector(HY_footerAtSection:)]) {
        return [self HY_footerAtSection:section];
    }
    return nil;
}

// 每一行返回指定的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if ([self respondsToSelector:@selector(HY_cellAtIndexPath:)]) {
        return [self HY_cellAtIndexPath:indexPath];
    }
    // 1. 创建cell
    HYBaseTableViewCell *cell = [HYBaseTableViewCell cellWithTableView:self.tableView];

    // 2. 返回cell
    return cell;
}

// 点击某一行 触发的事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HYBaseTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([self respondsToSelector:@selector(HY_didSelectCellAtIndexPath:cell:)]) {
        [self HY_didSelectCellAtIndexPath:indexPath cell:cell];
    }
}

- (UIView *)refreshHeader {
    return self.tableView.mj_header;
}

// 设置分割线偏移间距并适配
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!self.needCellSepLine) return ;
    UIEdgeInsets edgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
    if ([self respondsToSelector:@selector(HY_sepEdgeInsetsAtIndexPath:)]) {
        edgeInsets = [self HY_sepEdgeInsetsAtIndexPath:indexPath];
    }
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) [tableView setSeparatorInset:edgeInsets];
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) [tableView setLayoutMargins:edgeInsets];
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) [cell setSeparatorInset:edgeInsets];
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) [cell setLayoutMargins:edgeInsets];
}

// 每一行的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self respondsToSelector:@selector(HY_cellheightAtIndexPath:)]) {
        return [self HY_cellheightAtIndexPath:indexPath];
    }
    return tableView.rowHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([self respondsToSelector:@selector(HY_sectionHeaderHeightAtSection:)]) {
        return [self HY_sectionHeaderHeightAtSection:section];
    }
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if ([self respondsToSelector:@selector(HY_sectionFooterHeightAtSection:)]) {
        return [self HY_sectionFooterHeightAtSection:section];
    }
    return 0.01;
}

- (NSInteger)HY_numberOfSections {
    return 0;
}

- (NSInteger)HY_numberOfRowsInSection:(NSInteger)section {
    return 0;
}

- (UITableViewCell *)HY_cellAtIndexPath:(NSIndexPath *)indexPath {
    return [HYBaseTableViewCell cellWithTableView:self.tableView];
}

- (CGFloat)HY_cellheightAtIndexPath:(NSIndexPath *)indexPath {
    return 0;
}

- (void)HY_didSelectCellAtIndexPath:(NSIndexPath *)indexPath cell:(HYBaseTableViewCell *)cell {
}

- (UIView *)HY_headerAtSection:(NSInteger)section {
    return [HYBaseTableHeaderFooterView headerFooterViewWithTableView:self.tableView];
}

- (UIView *)HY_footerAtSection:(NSInteger)section {
    return [HYBaseTableHeaderFooterView headerFooterViewWithTableView:self.tableView];
}

- (CGFloat)HY_sectionHeaderHeightAtSection:(NSInteger)section {
    return 0.01;
}

- (CGFloat)HY_sectionFooterHeightAtSection:(NSInteger)section {
    return 0.01;
}

- (UIEdgeInsets)HY_sepEdgeInsetsAtIndexPath:(NSIndexPath *)indexPath {
    return UIEdgeInsetsMake(0, 15, 0, 0);
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
